<?php

/**

 * 竞标控制器

 */

namespace app\admin\controller;

use app\admin\traits\AdminSettingForm;
use app\admin\traits\SettingContent;
use app\common\model\Project;
use app\common\model\ProjectLog;
use app\common\model\User;
use app\common\validate\ProjectLogValidate;
use Exception;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\db\Query;
use think\Request;
use think\response\Json;

class ProjectLogController extends AdminBaseController {

	use AdminSettingForm;

	use SettingContent;

	protected array $authExcept = [

		'admin/project_log/template',

	];

	protected array $loginExcept = [

		'admin/project_log/template',

	];

	/**

	 * 列表

	 * @param Request $request

	 * @param ProjectLog $model

	 * @return string

	 * @throws Exception

	 */

	public function index(Request $request, ProjectLog $model): string {

		$param = $request->param();

		$data = $model->with(['project', 'user'])->scope('where', $param)

			->paginate([

				'list_rows' => $this->admin['admin_list_rows'],

				'var_page' => 'page',

				'query' => $request->get(),

			]);

		// 关键词，排序等赋值

		$this->assign($request->get());

		$this->assign([

			'data' => $data,

			'page' => $data->render(),

			'total' => $data->total(),

			'project_list' => Project::select(),

			'user_list' => User::where('user_level_id', 1)->select(),

			'status_list' => ProjectLog::STATUS_LIST,

		]);

		return $this->fetch();

	}

	/**

	 * 添加

	 * @param Request $request

	 * @param ProjectLog $model

	 * @param ProjectLogValidate $validate

	 * @return string|Json

	 * @throws Exception

	 */

	public function add(Request $request, ProjectLog $model, ProjectLogValidate $validate) {

		if ($request->isPost()) {

			$param = $request->param();

			try {

				$param['detail'] = $this->getDetail2($param);

			} catch (RuntimeException $exception) {

				return admin_error($exception->getMessage());

			}

			$validate_result = $validate->scene('admin_add')->check($param);

			if (!$validate_result) {

				return admin_error($validate->getError());

			}

			$result = $model::create($param);

			$url = URL_BACK;

			if (isset($param['_create']) && (int) $param['_create'] === 1) {

				$url = URL_RELOAD;

			}

			return $result ? admin_success('添加成功', [], $url) : admin_error();

		}

		$this->assign([

			'project_list' => Project::select(),

			'user_list' => User::where('user_level_id', 1)->select(),

			'status_list' => ProjectLog::STATUS_LIST,

		]);

		return $this->fetch();

	}

	/**

	 * 修改

	 * @param $id

	 * @param Request $request

	 * @param ProjectLog $model

	 * @param ProjectLogValidate $validate

	 * @return string|Json

	 * @throws Exception

	 */

	public function edit($id, Request $request, ProjectLog $model, ProjectLogValidate $validate) {

		$data = $model->findOrEmpty($id);

		if ($request->isPost()) {

			$param = $request->param();

			try {

				$param['detail'] = $this->getDetail2($param);

			} catch (RuntimeException $exception) {

				return admin_error($exception->getMessage());

			}

			$check = $validate->scene('admin_edit')->check($param);

			if (!$check) {

				return admin_error($validate->getError());

			}

			$result = $data->save($param);

			return $result ? admin_success('修改成功', [], URL_BACK) : admin_error('修改失败');

		}

		$this->assign([

			'data' => $data,

			'project_list' => Project::select(),

			'user_list' => User::where('user_level_id', 1)->select(),

			'status_list' => ProjectLog::STATUS_LIST,

		]);

		return $this->fetch('add');

	}

	public function info($id, Request $request, ProjectLog $model, ProjectLogValidate $validate) {

		$data = $model->with(['project'])->findOrEmpty($id);
		if ($data) {
			$detail = $data->detail;

			$bestAllMoney = 0;
			foreach ($detail as $key => $value) {
				$bestAllMoney += $value['price'];
			}
			$data['best_all_money'] = $bestAllMoney;

		}

		$this->assign([

			'data' => $data,

			'project_list' => Project::select(),

			'user_list' => User::where('user_level_id', 1)->select(),

			'status_list' => ProjectLog::STATUS_LIST,

		]);

		return $this->fetch();

	}

	/**

	 * 删除

	 * @param mixed $id

	 * @param ProjectLog $model

	 * @return Json

	 */

	public function del($id, ProjectLog $model): Json {

		$check = $model->inNoDeletionIds($id);

		if (false !== $check) {

			return admin_error('ID为' . $check . '的数据不能被删除');

		}

		$result = $model::destroy(static function ($query) use ($id) {

			/** @var Query $query */

			$query->whereIn('id', $id);

		});

		return $result ? admin_success('删除成功', [], URL_RELOAD) : admin_error('删除失败');

	}

	public function template($id, Request $request, ProjectLog $model) {

		$data = $model->with(['user'])->findOrEmpty($id);

		$this->assign([

			'data' => $data,

		]);

		return $this->fetch();

	}

	public function disable($id, ProjectLog $model): Json {

		$result = $model->whereIn('id', $id)->update(['status' => 3]);

		return $result ? admin_success('操作成功', [], URL_RELOAD) : admin_error();

	}

	public function export($id, Request $request, ProjectLog $model) {

		$param = $request->param();

		$info = $model->with(['project', 'user'])->findOrEmpty($id);

		$name = $info['project']['title'];

		$spreadsheet = new Spreadsheet();

		$sheet = $spreadsheet->setActiveSheetIndex(0);

		$sheet->mergeCells("A1:F1"); //合并单元格

		$sheet->mergeCells("A2:B2"); //合并单元格

		$sheet->mergeCells("C2:D2"); //合并单元格

		$sheet->setCellValue("A1", $info['user']['company']['company_name']);

		$sheet->setCellValue("A2", "统一社会信用代码");

		$sheet->setCellValue("C2", $info['user']['company']['code']);

		$sheet->setCellValue("E2", "总价");

		$sheet->setCellValue("F2", $info['all_money']);

		$sheet->setCellValue("A3", "序号");

		$sheet->setCellValue("B3", "名称");

		$sheet->setCellValue("C3", "规格");

		$sheet->setCellValue("D3", "单位");

		$sheet->setCellValue("E3", "数量");

		$sheet->setCellValue("F3", "最高报价");

		$sheet->setCellValue("G3", "报价");

		$sheet->setCellValue("H3", "产地");

		$char_index = range('B', 'Z');

		// 处理超过26列

		$a = 'A';

		foreach ($char_index as $item) {

			$char_index[] = $a . $item;

		}

		foreach ($info['detail'] as $key => $val) {
			unset($val['compute_id']);
			$row = $key + 4;

			$col = 0;
			$sheet->setCellValue("A" . $row, $key + 1);

			foreach ($val as $k => $v) {

				$sheet->setCellValue($char_index[$col] . $row, $v);

				$col++;

			}

		}

		$spreadsheet->getActiveSheet()->setTitle('Sheet1');

		header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');

		header('Content-Disposition: attachment;filename="' . $name . '.xlsx"');

		header('Cache-Control: max-age=0');

		$objWriter = IOFactory::createWriter($spreadsheet, 'Xlsx');

		$objWriter->save('php://output');

		exit();

	}

	// public function export($id, ProjectLog $model) {

	// 	$info = $model->with(['project', 'user'])->findOrEmpty($id);

	// 	$data = file_get_contents('https://hq.leyuansm.cn/admin/project_log/template?id=' . $id);

	// 	require_once '../vendor/tecnickcom/tcpdf/tcpdf.php';

	// 	// 初始化对象

	// 	$pdf = new TCPDF();

	// 	$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

	// 	$pdf->SetCreator($info['project']['title']);

	// 	$pdf->SetAuthor($info['project']['title']);

	// 	$pdf->SetTitle($info['project']['title']);

	// 	$pdf->SetSubject($info['project']['title']);

	// 	$pdf->SetKeywords('PDF');

	// 	$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_RIGHT, PDF_MARGIN_TOP);

	// 	$pdf->SetHeaderMargin(0);

	// 	$pdf->SetFooterMargin(PDF_MARGIN_BOTTOM);

	// 	$pdf->setPrintHeader(false);

	// 	$pdf->setPrintFooter(false);

	// 	$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

	// 	$pdf->SetFont('stsongstdlight', '', 14);

	// 	$pdf->AddPage();

	// 	//$data = file_get_contents('./project_log/template?id=' . $id);

	// 	$pdf->Ln();

	// 	$pdf->Ln();

	// 	$pdf->writeHTMl($data, true, false, false, false);

	// 	$pdf->Output($info['project']['title'] . '.pdf', 'D');

	// }

}
